package com.uni.bgController;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.uni.common.entity.Attachment;
import com.uni.common.util.SystemConfig;
import com.uni.config.FastDFSClient;
import com.uni.service.impl.AttachmentService;
import com.uni.web.util.Encodes;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文件上传
 * @author yanzheng_Yu
 *
 */
@Controller
@RequestMapping("file")
public class FileUploadControllerbg {
	
	@Autowired
	private AttachmentService attachmentService;
	 /**
     * AJAX批量上传图片文件
     *
     * 文件上传目录
     *            水印
     *            压缩
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadFile",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFile(
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<MultipartFile> uploadFiles = getUploadFiles(request);
        Map<String, Object> result = Maps.newHashMap();
        List<Attachment> atts = Lists.newArrayList();
        for(int i=0; i < uploadFiles.size(); i++) {
        	MultipartFile file = uploadFiles.get(i);
        	String encodeFilename = Encodes.encodeUrlSafeuni64(DigestUtils.md5DigestAsHex(file.getBytes()).getBytes());
        	Attachment att = attachmentService.findByFileId(encodeFilename);
        	if(att == null) {
//        		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
//        		String path = uploadFile(file,encodeFilename + "." + extension);
				String originalFilename = file.getOriginalFilename();
				// 获取扩展名
				String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
				FastDFSClient client = new FastDFSClient();
				String url = client.uploadFile(file.getBytes(), substring);
				String resoult=url;
				att = new Attachment();
        		att.setFileId(encodeFilename);
        		att.setFileName(file.getOriginalFilename());
        		att.setFileSize(file.getSize());
        		att.setFileExtension(substring);
        		att.setFileUrl(resoult);
        		att.setUpdateTime(new Date());
        		att.setCreateTime(new Date());
        		attachmentService.insert(att);
        	}
        	att.setAbsoluteFileUrl(SystemConfig.basePath + "/"+att.getFileUrl());
        	atts.add(att);
        }
        result.put("files", atts);
        return result;
    }
    
    private String uploadFile(MultipartFile file, String fileName) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String path = "/" + sdf.format(new Date()) + "/";
		FileOutputStream out = null;
		InputStream in = null;
		try {
			in = file.getInputStream();
			File f = new File(SystemConfig.filePath + path);
			if(!f.exists()) {
				f.mkdirs();
			}
			out = new FileOutputStream(SystemConfig.filePath + path + fileName);
			if(fileName.endsWith("png")) {
				BufferedImage bi = ImageIO.read(in);
				ImageIO.write(bi, "png", out);
			} else {
				IOUtils.copy(in, out);
			}
		} catch (IOException e) {
			e.printStackTrace();
			if(in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			if(out != null) {
				try {
					out.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		return path + fileName;
	}
    
    public static String uploadFile(byte[] buf, String fileName) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String path = "/" + sdf.format(new Date()) + "/";
		InputStream in = null;
		FileOutputStream out = null;
		try {
			in = new ByteArrayInputStream(buf);
			File f = new File(SystemConfig.filePath + path);
			if(!f.exists()) {
				f.mkdirs();
			}
			out = new FileOutputStream(SystemConfig.filePath + path + fileName);
			if(fileName.endsWith("png")) {
				BufferedImage bi = ImageIO.read(in);
				ImageIO.write(bi, "png", out);
			} else {
				IOUtils.copy(in, out);
			}
		} catch (IOException e) {
			e.printStackTrace();
			if(in != null) {
				try {
					in.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			if(out != null) {
				try {
					out.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		return path + fileName;
	}


	/**
     * 获得批量的上传文件集合
     *
     * @param request
     * @return
     */
    public List<MultipartFile> getUploadFiles(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<MultipartFile> files = new ArrayList<MultipartFile>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            files.add(mf);
        }
        return files;
    }
}
 